const request = require('../../utils/request')
const { signIn, getAllSign, getSummary, getRules } = require('../../utils/Integral')

function getDays(year, month, signedDays) {
  const days = []
  const date = new Date(year, month - 1, 1)
  const today = new Date()
  const firstDay = date.getDay()
  const lastDate = new Date(year, month, 0).getDate()
  const isCurrentMonth = year === today.getFullYear() && month === today.getMonth() + 1
  // 补齐前面空白
  for (let i = 0; i < firstDay; i++) days.push({ day: '', signed: false, disabled: true })
  for (let d = 1; d <= lastDate; d++) {
    const isToday = isCurrentMonth && d === today.getDate()
    const signed = signedDays.includes(d)
    // 只允许今天及之前可点击，后面日期禁用
    const disabled = isCurrentMonth ? d > today.getDate() : (year > today.getFullYear() || (year === today.getFullYear() && month > today.getMonth() + 1))
    days.push({ day: d, isToday, signed, disabled })
  }
  return days
}

Page({
  data: {
    year: 2024,
    month: 6,
    weekDays: ['日','一','二','三','四','五','六'],
    days: [],
    signedDays: [], // 不再用测试数据
    allSignDates: [], // 新增：存储所有签到原始数据
    integral: 0, // 测试积分
    showRuleModal: false,
    ruleHtml: '',
    todayStr: '',
    sliderLeft: 0,
    sliderMax: 0,
    sliderDragging: false,
    todaySigned: false // 今天是否已签到
  },
  async onLoad() {
    const now = new Date()
    const todayStr = `${now.getFullYear()}-${(now.getMonth() + 1).toString().padStart(2, '0')}-${now.getDate().toString().padStart(2, '0')}`;
    this.setData({ year: now.getFullYear(), month: now.getMonth() + 1, todayStr })
    // getSummary和getAllSign并行
    getSummary(false).then(res => {
      this.setData({ integral: res || 0 })
    }).catch(() => {
      this.setData({ integral: 0 })
    })
    getAllSign().then(res => {
      this.setData({ allSignDates: res || [] }, () => {
        this.updateSignedDays()
        // 检查今天是否已签到
        this.checkTodaySigned()
      })
    }).catch(() => {
      this.updateDays()
    })
  },
  onReady() {
    // 计算滑块最大可滑动距离（用px）
    const query = wx.createSelectorQuery().in(this);
    query.select('.signin-slider-bar').boundingClientRect();
    query.select('.signin-slider-btn').boundingClientRect();
    query.exec(res => {
      if (res && res[0] && res[1]) {
        const max = res[0].width - res[1].width;
        this.setData({ sliderMax: max, sliderLeft: 0 });
      }
    });
  },
  onSliderStart(e) {
    this.data.sliderDragging = true;
    this.data.startX = e.touches[0].clientX;
    this.data.startLeft = this.data.sliderLeft;
  },
  onSliderMove(e) {
    if (!this.data.sliderDragging) return;
    const moveX = e.touches[0].clientX - this.data.startX;
    let left = this.data.startLeft + moveX;
    if (left < 0) left = 0;
    if (left > this.data.sliderMax) left = this.data.sliderMax;
    this.setData({ sliderLeft: left });
  },
  onSliderEnd(e) {
    this.data.sliderDragging = false;
    if (this.data.sliderLeft >= this.data.sliderMax - 10) {
      this.setData({ sliderLeft: this.data.sliderMax });
      this.onSignIn();
      setTimeout(() => {
        this.setData({ sliderLeft: 0 });
      }, 600);
    } else {
      this.setData({ sliderLeft: 0 });
    }
  },
  updateSignedDays() {
    // 根据当前year和month过滤allSignDates
    const { year, month, allSignDates } = this.data
    const signedDays = (allSignDates || []).map(item => {
      if (!item.signDate) return null;
      const parts = item.signDate.split('-');
      if (parseInt(parts[0]) === year && parseInt(parts[1]) === month) {
        return parseInt(parts[2]);
      }
      return null;
    }).filter(d => d);
    this.setData({ signedDays }, this.updateDays)
  },
  checkTodaySigned() {
    const now = new Date()
    const todayStr = `${now.getFullYear()}-${(now.getMonth() + 1).toString().padStart(2, '0')}-${now.getDate().toString().padStart(2, '0')}`
    const { allSignDates } = this.data
    const todaySigned = (allSignDates || []).some(item => item.signDate === todayStr)
    this.setData({ todaySigned })
  },
  updateDays() {
    const { year, month, signedDays } = this.data
    this.setData({ days: getDays(year, month, signedDays) })
  },
  onPrevMonth() {
    let { year, month } = this.data
    month--
    if (month < 1) {
      month = 12
      year--
    }
    this.setData({ year, month }, this.updateSignedDays)
  },
  onNextMonth() {
    let { year, month } = this.data
    month++
    if (month > 12) {
      month = 1
      year++
    }
    this.setData({ year, month }, this.updateSignedDays)
  },
  onSignIn() {
    const now = new Date()
    const today = now.getDate()
    const { year, month, signedDays } = this.data
    if (signedDays.includes(today)) {
      wx.showToast({ title: '今日已签到', icon: 'none' })
      return
    }
    if (year === now.getFullYear() && month === now.getMonth() + 1) {
      wx.showLoading({ title: '签到中', mask: true })
      // 请求网络签到接口
      signIn({ date: now }).then(async () => {
        wx.hideLoading()
        signedDays.push(today)
        this.setData({ signedDays }, this.updateDays)
        this.setData({ todaySigned: true })
        wx.showToast({ title: '签到成功', icon: 'success' })
        // 签到成功后更新积分
        try {
          const res = await getSummary(false)
          this.setData({ integral: res || 0 })
        } catch {
          // 不处理
        }
      }).catch(() => {
        wx.hideLoading()
        wx.showToast({ title: '签到失败', icon: 'none' })
      })
    } else {
      wx.showToast({ title: '只能签到本月', icon: 'none' })
    }
  },
  onIntegralHistory() {
    wx.showToast({ title: '积分历史功能开发中', icon: 'none' })
  },
  onIntegralRule() {
    wx.showLoading({ title: '加载中', mask: true })
    getRules().then(res => {
      wx.hideLoading()
      this.setData({
        showRuleModal: true,
        ruleHtml: res || '<p>暂无规则</p>'
      })
    }).catch(() => {
      wx.hideLoading()
      this.setData({
        showRuleModal: true,
        ruleHtml: '<p>暂无规则</p>'
      })
    })
  },
  onCloseRule() {
    this.setData({ showRuleModal: false })
  }
}) 